package main;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import javax.imageio.ImageIO;
import com.alibaba.fastjson.JSONObject;
import sun.misc.BASE64Decoder;

public class BodySegSample {
    public static String BODYSEG_URL = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg";
    //accessToken需要通过下面的连接得到（其中client_id是创建的应用的API Key, client_secret是Screct Key）
    //https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=rXyhRA4gGEPX8Iif4G0NLqLt&client_secret=gEGP0nozLuDAfhiRgkMGEEXH9QMVkn3C

    /**
     * @param filePath 图片路径
     * @throws Exception
     */
    public static String doSeg(String filePath) throws Exception {
        String accessToken = "24.3183fc0a05e87924685df05a36cc186f.2592000.1600918997.282335-19835729";
        String result = getBodySegResult(filePath, accessToken);
        JSONObject jsonObject = JSONObject.parseObject(result);
        //图片转BufferedImage对象
        BufferedImage image = ImageIO.read(new File(filePath));
        //对接口返回的labelmapbase64进行处理  并拿图片的原始宽高
//        convert(jsonObject.getString("labelmap"),image.getWidth(),image.getHeight());
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String destFileName = now.format(formatter) + StringHelper.getAlphaNumericString(8) + ".png";
        String destFilePath = PathUtil.PathPrefix + destFileName;
        GenerateImage(jsonObject.getString("foreground"), destFilePath);
        return destFilePath;
    }
    /**
     * @param imagePath 图片本地路径
     * @param accessToken 应用AccessToken
     * @return String
     * @throws Exception
     */
    private static String getBodySegResult(String imagePath, String accessToken) throws Exception {
        byte[] imgData = FileUtil.readFileByBytes(imagePath);
        String imgStr = Base64Util.encode(imgData);
        String param = "image=" + URLEncoder.encode(imgStr, "UTF-8");
        String result = HttpUtil.post(BODYSEG_URL, accessToken, param);
        return result;
    }
    /**
     * 图像转换
     * @param labelmapBase64 分割结果图片，检测出的二值图像，base64编码之后
     * @param realWidth 图片原始高度px
     * @param realHeight 图片原始宽度px
     */
    public static void convert(String labelmapBase64, int realWidth, int realHeight) {
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] bytes = base64Decoder.decodeBuffer(labelmapBase64);
            InputStream is = new ByteArrayInputStream(bytes);
            BufferedImage image = ImageIO.read(is);
            BufferedImage newImage = resize(image, realWidth, realHeight);
            BufferedImage grayImage = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_BYTE_GRAY);//灰度图
            for(int i= 0 ; i < realWidth ; i++){
                for(int j = 0 ; j < realHeight; j++){
                    int rgb = newImage.getRGB(i, j);
                    grayImage.setRGB(i, j, rgb * 255);  //将像素存入缓冲区 这一步很重要哦
                }
            }
            File newFile = new File(PathUtil.PathPrefix + "gray001.png");
            ImageIO.write(grayImage, "png", newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 重置图片大小
     * @param img 图片数据
     * @param newW 图片宽度
     * @param newH 图片高度
     * @return
     */
    public static BufferedImage resize(BufferedImage img, int newW, int newH) {
        Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
        BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = dimg.createGraphics();
//        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();
        return dimg;
    }

    public static boolean GenerateImage(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            // Base64解码
            byte[] b = decoder.decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) { // 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath); // 新生成的图片
            out.write(b);
            out.flush();
            out.close();
            System.out.println("保存成功" + imgFilePath);
            return true;
        } catch(Exception e) {
            System.out.println("出错了" + e.getMessage());
            return false;
        }
    }
}
